package com.demo.testWork.testCase;

import com.demo.config.LogInit;
import com.demo.config.ProjectSettings;
import com.demo.config.SpringConfig;
import com.demo.core.listenerCore.TestngISuiteListener;
import com.demo.testWork.base.*;
import com.demo.testWork.step.LoginStep;
import io.qameta.allure.Step;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;

import javax.annotation.Resource;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Properties;

@Listeners({TestngISuiteListener.class})
@Component
public class BaseCase{

    public Logger logger = LogInit.getInstance();
    @Resource
    public HomePage homePage;
    @Resource
    public LoginPage loginPage;
    @Resource
    public LoginStep loginStep;

    protected static Properties projectSetting = ProjectSettings.getInstance();

//    @BeforeSuite
    public void setBeansConfig() {
        ApplicationContext appCtx = new AnnotationConfigApplicationContext(SpringConfig.class);
        BaseCase baseCase = (BaseCase)appCtx.getBean("baseCase");
        Field[] fields= baseCase.getClass().getDeclaredFields();
        String fieldName ="";
        Object ob = null;

        try {
            for (Field field : fields) {
                ob = field.get(baseCase);
                fieldName = field.getName();
                Annotation[] annotations = ob.getClass().getDeclaredAnnotations();
                for (Annotation annotation : annotations) {
                    if (annotation.toString().contains("Service")) {
                        this.getClass().getField(fieldName).set(this, ob);
                    }
                }
            }
        } catch (IllegalAccessException | NoSuchFieldException e) {
            logger.info(e);
        }
    }

    @Step("API Test Init")
    @BeforeClass(enabled = true)
    public void setUp(){
        setBeansConfig();
        logger.info("-------------------------Start Test Case " + this.getClass().getSimpleName() + "-------------------------");
    }

    @Step("API Test Recycle")
    @AfterClass(enabled = true)
    public void tearDown(){
        logger.info("-------------------------End Test Case " + this.getClass().getSimpleName() + "-------------------------");
    }
}
